const flyData = []; // 无人机列表
let start = Cesium.JulianDate.fromDate(new Date("2022-10-27 00:00:00")); // 飞行的开始时间
let time = 1666800000000; // 飞行的当前时间
let stop = null; // 飞行的结束时间
let modelArray = {}; // 记录所有无人机模型
const positionProperty = {}; // 记录所有无人机的信息，用于计算无人机的姿态
let flySecondsS = 0; // 无人机的飞行时长
let checkEntity = null; // 当前选中的无人机实体
let currentJulianDate = null; // JulianDate 格式的当前时间
let removePath = false; // 是否删除航迹
let drawPath = false; // 是否开始绘制航迹
const uavLength = 4; // 无人机个数
let count = 0;
let random = 2;
let direction = 1;
let dou = [1, 1, 1, 1];

// 新建无人机模型
function addModelEntity(uavInfo) {
  if (!uavInfo) return;
  const position = Cesium.Cartesian3.fromDegrees(
    uavInfo.longitude,
    uavInfo.latitude,
    uavInfo.height
  );
  let minimumPixelSize = 32;
  let uri = "../model/uav.glb";
  if (+uavInfo.model === 1) {
    minimumPixelSize = 64;
    uri = "../model/15-0.glb";
  } else if (+uavInfo.model === 2) {
    uri = "../model/uav2.glb";
    minimumPixelSize = 64;
  };
  const uavModel = viewer.entities.add({
    position: position,
    model: {
      uri,
      scale: +uavInfo.model === 2 ? 0.1 : 0.05,
      minimumPixelSize,
      color: Cesium.Color.fromCssColorString("white"),
    },
    path: {
      width: 5,
      material: Cesium.Color.fromCssColorString("red"),
    },
    label: {
      text: `无人机${+uavInfo.uavSn + 1}(型号${+uavInfo.model + 1})`,
      font: "12px",
      showBackground: true,
      backgroundColor: Cesium.Color.fromCssColorString("#999"),
      backgroundPadding: new Cesium.Cartesian2(8, 4),
      pixelOffset: new Cesium.Cartesian2(40, -20),
      horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
      verticalOrigin: Cesium.VerticalOrigin.TOP,
    },
  });
  console.log("加载无人机", uavInfo);
  return uavModel;
};

// 无人机飞行函数
function flyEvent (uavInfo, index) {
  if (!uavInfo) return;
  // JulianDate 格式的当前时间
  currentJulianDate = Cesium.JulianDate.fromDate(new Date(time));
  // 如果航迹被删除了，重新绘制航迹
  if (currentJulianDate && !removePath && drawPath) {
    start = currentJulianDate;
    index === uavLength - 1 && (drawPath = false);
    modelArray[uavInfo.uavSn].path = new Cesium.PathGraphics({
      width: 5,
      material: Cesium.Color.fromCssColorString("red"),
    });
    // 删除航迹
  } else if (removePath && !drawPath) {
    modelArray[uavInfo.uavSn].path = undefined;
    if (index === uavLength - 1) {
      removePath = false;
      drawPath = true;
    };
  };
  // 设置飞行结束时间，三个无人机共用一个时间
  if (index === 0) {
    stop = Cesium.JulianDate.addSeconds(
      start,
      flySecondsS,
      new Cesium.JulianDate()
    );
    viewer.clock.currentTime = currentJulianDate.clone();
    viewer.clock.startTime = start.clone();
    viewer.clock.stopTime = stop.clone();
    viewer.clock.clockRange = Cesium.ClockRange.CLAMPED;
    // viewer.timeline.zoomTo(start, stop);
    // 增加飞行时长
    flySecondsS++;
    // 飞行时间增加 1000 ms
    time += 1000;
  };
  const position = Cesium.Cartesian3.fromDegrees(
    uavInfo.longitude,
    uavInfo.latitude,
    uavInfo.height,
  );
  // 增加当前时间的位置信息
  positionProperty[uavInfo.uavSn].addSample(currentJulianDate, position);
  // 绘制当前无人机的航迹
  modelArray[uavInfo.uavSn].availability = new Cesium.TimeIntervalCollection([
    new Cesium.TimeInterval({
      start,
      stop,
      data: position,
    })
  ]);
  // 修改当前无人机的位置
  modelArray[uavInfo.uavSn].position = positionProperty[uavInfo.uavSn];
  // 设置当前无人机的姿态
  modelArray[uavInfo.uavSn].orientation = new Cesium.VelocityOrientationProperty(positionProperty[uavInfo.uavSn]);
  // 获获取无人机在当前时间的位置信息
  // const currentPosition = modelArray[uavInfo.uavSn].position.getValue(currentJulianDate);
};

// 创建指定多个无人机并设置初始随机位置信息
for(let i = 0; i < uavLength; i++) {
  flyData.push({
    uavSn: i,
    model: (Math.random() * 2).toFixed(0),
    longitude: (Math.random() * 60 + 70).toFixed(4),
    latitude: (Math.random() * 40 + 10).toFixed(4),
    height: 10000,
  });
};

// 设置随机增加的经纬度
const a = 0.0001;
const b = 0.0002;
const c = 0.0003;
const d = 0.0004;
const number = [a, b, c, d];
function getRandom(data) {
  if (!data) return;
  const x = (Math.random() * 3).toFixed(0);
  return (+data + number[x]).toFixed(4);
};

// 每 30ms 进行一次飞行，若是第一次进入则创建无人机模型
setInterval(() => {
  if (!flyData.length) return;
  flyData.forEach((item, index) => {
    if (!modelArray[item.uavSn]) {
      modelArray[item.uavSn] = addModelEntity(item);
      positionProperty[item.uavSn] = new Cesium.SampledPositionProperty();
    } else {
      // 随机增加
      // item.longitude = getRandom(item.longitude);
      // item.latitude = getRandom(item.latitude);
      // 平滑增加
      count++;
      if (count % 100 == 0) {
        random = (Math.random() * 2).toFixed(0);
        direction = (Math.random() * 2 - 1).toFixed(0);
        direction = direction == 0 ? 1 : direction;
        dou[0] = (Math.random() * 3 + 1).toFixed(0);
        dou[1] = (Math.random() * 3 + 1).toFixed(0);
        dou[2] = (Math.random() * 3 + 1).toFixed(0);
        dou[3] = (Math.random() * 3 + 1).toFixed(0);
      };
      random == 0 && (item.longitude = (+item.longitude + 0.0001 * +direction * +dou[0]).toFixed(4));
      random == 1 && (item.latitude = (+item.latitude + 0.0001 * +direction * +dou[1]).toFixed(4));
      if (random == 2) {
        item.longitude = (+item.longitude + 0.0001 * +direction * +dou[2]).toFixed(4);
        item.latitude = (+item.latitude + 0.0001 * +direction * +dou[3]).toFixed(4);
      };
      flyEvent(item, index);
    };
  });
}, 30);

// 单击无人机模型进行镜头跟随
const uavHandler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
const LEFT_CLICK = Cesium.ScreenSpaceEventType.LEFT_CLICK;
uavHandler.setInputAction(event => {
  let entity = viewer.scene.drillPick(event.position, 1)[0];
  if (!entity) return;
  entity = entity.id;
  if (!entity.model) return;
  if (!checkEntity || checkEntity && checkEntity !== entity) {
    checkEntity = entity;
  } else if (checkEntity && checkEntity === entity) {
    checkEntity = null;
  };
  viewer.trackedEntity = checkEntity;
}, LEFT_CLICK);

// 清除所有无人机的航迹
function clearPath() {
  removePath = true;
};